<template>
    <div class="entry">
        <div class="form-card">
            <div class="input-wrapper">
                <p class="label">加工费</p>
                <div class="input-box">
                    <van-radio-group
                        v-model="radio"
                        direction="horizontal"
                        icon-size="16px"
                        checked-color="#50b1c1"
                        @change="handleRadio"
                    >
                        <van-radio :name="1">是</van-radio>
                        <van-radio :name="0">否</van-radio>
                    </van-radio-group>
                </div>
            </div>
            <div class="input-wrapper" v-if="radio">
                <p class="label">客户名称</p>
                <div class="input-box">
                    <el-select
                        class="input"
                        v-clickoutside
                        v-model="searchKey"
                        filterable
                        remote
                        reserve-keyword
                        placeholder="请选择客户名称"
                        :remote-method="getbills"
                        :loading="loading"
                        @change="getBillsDetail('')"
                    >
                        <el-option v-for="item in billsList" :key="item.id" :label="item.title" :value="item.id">
                        </el-option>
                    </el-select>
                    <van-icon name="arrow" />
                </div>
            </div>
            <div class="input-wrapper" v-if="radio">
                <p class="label">账单编号</p>
                <div class="input-box">
                    <el-select
                        class="input"
                        v-model="billsKey"
                        v-clickoutside
                        filterable
                        remote
                        reserve-keyword
                        placeholder="请选择账单编号"
                        :remote-method="getBillsDetail"
                        :loading="loading"
                        @change="handleChange"
                    >
                        <el-option
                            v-for="item in billsDetailList"
                            :key="item.id"
                            :label="item.order_sn"
                            :value="item.id"
                        >
                        </el-option>
                    </el-select>
                    <van-icon name="arrow" />
                </div>
            </div>
            <div class="input-wrapper">
                <p class="label">入账账户</p>
                <div class="input-box">
                    <el-select
                        class="input"
                        v-model="accountsKey"
                        v-clickoutside
                        filterable
                        remote
                        reserve-keyword
                        placeholder="请选择入账账户"
                        :remote-method="getAccounts"
                        :loading="loading"
                    >
                        <el-option v-for="item in accountsList" :key="item.id" :label="item.title" :value="item.id">
                        </el-option>
                    </el-select>
                    <van-icon name="arrow" />
                </div>
            </div>
            <div class="input-wrapper" v-if="!radio">
                <p class="label">入账类别</p>
                <div class="input-box">
                    <!-- <input type="text" class="input" placeholder="请输入客户名称"> -->
                    <el-select class="input" v-model="financesKey" placeholder="请选择入账类别">
                        <el-option v-for="item in financesList" :key="item.id" :label="item.title" :value="item.id">
                        </el-option>
                    </el-select>
                    <van-icon name="arrow" />
                </div>
            </div>
            <div class="input-wrapper">
                <p class="label">入账时间</p>
                <div class="input-box">
                    <input
                        type="text"
                        v-model="time"
                        readonly
                        class="input"
                        placeholder="请选择入账时间"
                        @click="show = true"
                    />
                    <van-icon name="arrow" />
                </div>
            </div>
            <div class="input-wrapper" v-if="radio && residue">
                <p class="label">应收金额</p>
                <div class="input-box">
                    <input v-model="residue" disabled="true" type="number" class="input" placeholder="请填写订单差价" />
                </div>
            </div>
            <div class="input-wrapper" v-if="radio">
                <p class="label">订单差价</p>
                <div class="input-box">
                    <input v-model="diff_amount" type="number" class="input" placeholder="请填写订单差价" />
                </div>
            </div>
            <div class="input-wrapper">
                <p class="label">入账金额</p>
                <div class="input-box">
                    <input v-model="amount" type="number" class="input" placeholder="请填写入账金额" />
                </div>
            </div>
        </div>

        <div class="input-wrapper">
            <p class="label">详细事项</p>
            <div class="input-box">
                <textarea v-model="remark" class="textarea" placeholder="请填写事项内容"></textarea>
            </div>
        </div>

        <div class="upload-wrapper">
            <p class="label">上传凭证</p>
            <p class="tips">*最多只能上传五张图片</p>
            <div class="upload-box">
                <div class="img-box" v-for="(item, index) in imgList" :key="index">
                    <img :src="item" alt="" class="img" @click.stop="previewImg" />
                    <img src="@/assets/images/img_05.png" @click.stop="delImg(index)" alt="" class="close" />
                </div>
                <van-uploader
                    :after-read="uploadImg"
                    v-if="imgList.length <= 4"
                    v-loading="uploadLoadingFitting"
                    accept="image/*"
                    multiple
                >
                    <img src="@/assets/images/img_04.png" alt="" class="upload-btn" />
                </van-uploader>
            </div>
        </div>
        <div class="submit-btn" @click="handleSubmit" v-loading="submitLoading">提交</div>
        <van-popup v-model="show" position="bottom">
            <van-datetime-picker
                v-model="currentDate"
                type="datetime"
                title="选择完整时间"
                :min-date="minDate"
                :max-date="maxDate"
                @cancel="show = false"
                @confirm="handleTime"
            />
        </van-popup>
        <van-popup v-model="showBill" closeable round position="bottom" :style="{ height: '380px' }">
            <div class="popup-box">
                <p>订单总金额：{{ billDetail.amount }}</p>
                <div class="list-box">
                    <p class="item" v-for="(item, index) in billDetail.items" :key="index">
                        {{ item.bill_time }} 入账{{ item.amount }}，差额：{{ item.diff_amount }}
                    </p>
                </div>
                <p>剩余：{{ residue }}</p>
            </div>
        </van-popup>
    </div>
</template>

<script>
import { Toast } from "vant";
import { v4 as uuidv4 } from "uuid";
import { ImagePreview } from "vant";
import moment from "moment";
export default {
    name: "entry",
    data() {
        return {
            searchKey: "",
            accountsKey: "",
            loading: false,
            billsList: [],
            accountsList: [],
            uploadLoadingFitting: false,
            imgList: [],
            financesList: [],
            financesKey: "",
            billsDetailList: [],
            billsKey: "",
            show: false,
            currentDate: new Date(),
            minDate: new Date(2020, 0, 1),
            maxDate: new Date(2100, 10, 1),
            time: "",
            amount: 0,
            diff_amount: 0,
            remark: "",
            submitLoading: false,
            billDetail: {},
            showBill: false,
            residue: "",
            isInit: true,
            isInitOrder: true,
            radio: 1,
            searchName: "",
            previewPicture: [],
        };
    },
    mounted() {
        if (this.$route.query.id) {
            this.reset();
            localStorage.removeItem("entryDataNew");
            this.searchKey = Number(this.$route.query.id);
            this.bill_info();
        }
        if (!this.time) this.time = this.getCurrentFormattedTime();
        this.getbills();
        this.getAccounts();
        this.getFinances();
    },
    watch: {
        diff_amount: {
            handler(val) {
                if (this.radio && this.residue) {
                    this.amount = (this.residue - val).toFixed(2);
                }
            },
            deep: true,
            immediate: true,
        },
    },
    methods: {
        handleRadio(val) {
            if (this.$route.query.info) return;
            this.searchKey = "";
            this.billsKey = "";
            this.diff_amount = "";
            this.financesKey = "";
        },
        handleChange(val) {
            this.billDetail = this.billsDetailList.find((item) => item.id == val);
            this.residue = this.billDetail?.no_pay;
            this.showBill = true;
        },
        async getbills(key) {
            this.loading = true;
            const res = await this.$api.bills({ key: key });
            this.loading = false;
            if (res.code == 1) {
                this.billsList = res.data;
                this.getBillsDetail("");
            }
        },
        async getAccounts(key) {
            this.loading = true;
            const res = await this.$api.accounts({ key: key });
            this.loading = false;
            if (res.code == 1) {
                this.accountsList = res.data;
            }
        },
        async getFinances() {
            const res = await this.$api.finances({ finance_cate_id: 1 });
            if (res.code == 1) {
                this.financesList = res.data;
            }
        },
        async getBillsDetail(key = "") {
            this.billsDetailList = [];
            this.residue = "";
            this.amount = "";
            this.diff_amount = "";
            if (!this.isInitOrder) this.billsKey = "";
            const res = await this.$api.bills_detail({
                hospital_id: this.$route.query.id ? this.$route.query.hospital_id : this.searchKey,
                key,
            });
            if (res.code == 1) {
                this.billsDetailList = res.data;
                if (this.isInitOrder && this.$route.query.id) {
                    this.isInitOrder = false;
                    this.billsKey = res.data.find((item) => item.order_sn == this.$route.query.order)?.id;
                    this.handleChange(this.billsKey);
                } else if (this.isInitOrder) {
                    this.isInitOrder = false;
                    if (this.billsKey) {
                        this.handleChange(this.billsKey);
                    }
                } else {
                    this.isInitOrder = false;
                }
            }
        },
        uploadImg(file) {
            if (file.length && file.length + this.imgList.length > 5) return Toast("超出上传文件限制");
            this.uploadLoadingFitting = true;
            this.$api
                .qiniu_token()
                .then((res) => {
                    const token = res.data.token;
                    const requestList = [];
                    const fileList = file.length ? file : [file];
                    fileList.forEach((item) => {
                        let form = new FormData();
                        form.append("token", token);
                        form.append("file", item.file);
                        form.append("key", uuidv4() + item.file.name.substring(item.file.name.lastIndexOf(".")));
                        requestList.push(this.$api.qiniup(form));
                    });

                    Promise.all(requestList)
                        .then((res) => {
                            this.uploadLoadingFitting = false;
                            res.forEach((response) => {
                                this.imgList.push("https://oss.ykshuju.com/" + response.key);
                            });
                        })
                        .catch((e) => {
                            this.uploadLoadingFitting = false;
                        });
                })
                .catch((e) => {
                    this.uploadLoadingFitting = false;
                });
            return false;
        },
        // 账单详情
        async bill_info() {
            const res = await this.$api.bill_info({ bill_id: this.$route.query?.id });
            if (res) {
                const { hospital } = res?.data;
                this.searchKey = hospital?.title;
            }
        },
        // 图片预览
        previewImg() {
            ImagePreview({
                images: this.imgList,
                closeable: true,
            });
        },
        delImg(index) {
            this.imgList.splice(index, 1);
        },
        handleTime(value) {
            this.time = moment(value).format("YYYY-MM-DD HH:mm:ss");
            this.show = false;
        },
        handleSubmit() {
            if (this.submitLoading) {
                return;
            }
            if (this.radio) {
                if (this.searchKey == "") {
                    Toast("请选择客户名称");
                    return;
                }
                if (this.billsKey == "") {
                    Toast("请选择账单编号");
                    return;
                }
            } else {
                if (this.financesKey == "") {
                    Toast("请选择入账类别");
                    return;
                }
            }

            if (this.accountsKey == "") {
                Toast("请选择入账账户");
                return;
            }
            if (this.time == "") {
                Toast("请选择入账时间");
                return;
            }
            if (!this.amount) {
                Toast("请填写入账金额");
                return;
            }
            // if (this.diff_amount && (this.diff_amount * 1 > this.amount * 1)) {
            //     Toast('订单差价不能大于入账金额')
            //     return
            // }
            this.submitLoading = true;
            this.$api
                .add_bill({
                    bill_id: this.billsKey,
                    // order_sn: this.billsKey,
                    diff_amount: this.diff_amount,
                    amount: this.amount,
                    bill_time: this.time,
                    images: this.imgList.join(","),
                    account_id: this.accountsKey,
                    remark: this.remark,
                    finance_id: this.financesKey,
                    type: "1",
                    is_subsidy: this.radio,
                })
                .then((res) => {
                    this.submitLoading = false;
                    if (res.code == 1) {
                        Toast("提交成功");
                        this.searchKey = "";
                        this.billsKey = "";
                        this.diff_amount = "";
                        this.amount = "";
                        this.time = "";
                        this.imgList = [];
                        this.accountsKey = "";
                        this.remark = "";
                        this.financesKey = "";
                        this.radio = 0;
                        localStorage.removeItem("entryDataNew");
                        this.$bus.$emit("submitList");
                    } else {
                        Toast(res.msg);
                    }
                })
                .catch((e) => {
                    this.submitLoading = false;
                });
        },
        getCurrentFormattedTime() {
            const now = new Date();
            const year = now.getFullYear();
            const month = String(now.getMonth() + 1).padStart(2, "0");
            const day = String(now.getDate()).padStart(2, "0");
            const hours = String(now.getHours()).padStart(2, "0");
            const minutes = String(now.getMinutes()).padStart(2, "0");
            const seconds = String(now.getSeconds()).padStart(2, "0");

            return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
        },
        reset() {
            (this.searchKey = ""),
                (this.accountsKey = ""),
                (this.loading = false),
                (this.billsList = []),
                (this.accountsList = []),
                (this.uploadLoadingFitting = false),
                (this.imgList = []),
                (this.financesList = []),
                (this.financesKey = ""),
                (this.billsDetailList = []),
                (this.billsKey = ""),
                (this.show = false),
                (this.currentDate = new Date()),
                (this.minDate = new Date(2020, 0, 1)),
                (this.maxDate = new Date(2100, 10, 1)),
                (this.time = ""),
                (this.amount = 0),
                (this.diff_amount = 0),
                (this.remark = ""),
                (this.submitLoading = false),
                (this.billDetail = {}),
                (this.showBill = false),
                (this.residue = ""),
                (this.isInit = true),
                (this.isInitOrder = true),
                (this.radio = 1),
                (this.searchName = ""),
                (this.previewPicture = []);
        },
    },
};
</script>

<style lang="scss" scoped>
.entry {
    min-height: 100vh;
    padding-top: 0.37rem;
    padding-bottom: 70px;
    background: linear-gradient(to bottom, #c4e1e6, #f6f6f6, #f6f6f6);

    .popup-box {
        padding: 20px;

        p {
            font-size: 14px;
            margin-bottom: 10px;
        }

        .list-box {
            padding: 10px 0;
            height: 280px;
            overflow-y: auto;

            .item {
            }
        }
    }

    .form-card {
        width: 9.2rem;
        margin: 0 auto;
        background-color: #fff;
        border-radius: 8px;
        overflow: hidden;
        margin-bottom: 0.24rem;

        .input-wrapper {
            padding: 0.77rem 0.4rem 0.27rem;
            border-bottom: 1px solid #eee;
            margin-bottom: 0;

            .label {
                margin-bottom: 0.32rem;
                font-size: 15px;
                color: #000;
            }

            .input-box {
                display: flex;
                align-items: center;

                .input {
                    font-size: 14px;
                    line-height: 22px;
                    flex: 1;
                    padding-right: 0.21rem;
                    color: #606266;

                    &::placeholder {
                        color: #c0c4cc;
                    }
                }

                ::v-deep .el-input__inner {
                    border: none;
                    padding-left: 0;
                    height: 22px;
                    font-size: 14px;
                    line-height: 22px;
                }

                ::v-deep .el-input__suffix {
                    display: none;
                }

                .van-icon {
                    color: #999999;
                }
            }
        }
    }

    .input-wrapper {
        padding: 0.77rem 0.4rem 0.27rem;
        background-color: #fff;
        width: 9.2rem;
        margin: 0 auto 0.48rem;
        border-radius: 8px;

        .label {
            margin-bottom: 0.32rem;
            font-size: 15px;
            color: #000;
        }

        .input-box {
            display: flex;
            align-items: center;

            .textarea {
                height: 66px;
                flex: 1;
                padding-right: 0.21rem;
                border: none;
                resize: none;
                font-size: 14px;
                line-height: 22px;
                color: #606266;

                &::placeholder {
                    color: #c0c4cc;
                }
            }
        }
    }

    .upload-wrapper {
        width: 9.2rem;
        margin: 0 auto 0.53rem;
        display: grid;
        grid-gap: 10px;

        .label {
            font-size: 15px;
            color: #000;
        }

        .tips {
            font-size: 12px;
            color: #d90013;
        }

        .upload-box {
            display: grid;
            grid-template-columns: repeat(3, 1fr);
            grid-gap: 10px;

            .img-box {
                position: relative;

                .img {
                    width: 100%;
                    height: 100%;
                    border-radius: 10px;
                    object-fit: cover;
                }

                .close {
                    display: block;
                    width: 0.48rem;
                    height: 0.48rem;
                    position: absolute;
                    top: 5px;
                    right: 5px;
                }
            }

            .upload-btn {
                display: block;
                width: 100%;
                height: 100%;
            }
        }
    }

    .submit-btn {
        width: 9.2rem;
        margin: 0 auto;
        height: 1.01rem;
        line-height: 1.01rem;
        text-align: center;
        background-color: #50b1c1;
        border-radius: 5px;
        font-size: 14px;
        color: #fff;
    }
}
</style>
